package com.iwe3.operation.controller;

import com.iwe3.operation.Enum.SystemEnum;
import com.iwe3.operation.common.LoginResult;
import com.iwe3.operation.common.R;
import com.iwe3.operation.dto.LoginDto;
import com.iwe3.operation.entity.ManagerEntity;

import com.iwe3.operation.handler.Asserts;
import com.iwe3.operation.service.IManagerService;
import com.iwe3.operation.util.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RequestMapping("/manager")
@RestController
public class ManagerController {

    @Value("${token.signature}")
    private String signature;
    private final RedisTemplate redisTemplate;
    private final IManagerService managerServiceImpl;


    public ManagerController(@Qualifier("redisTemplate") RedisTemplate redisTemplate, IManagerService managerServiceImpl) {
        this.redisTemplate = redisTemplate;
        this.managerServiceImpl = managerServiceImpl;
    }

    @PostMapping("/login")
    public R login( @RequestBody LoginDto dto) {

        HttpServletRequest request =
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        ManagerEntity manager = managerServiceImpl.login(dto);
        Asserts.fail(Objects.isNull(manager), SystemEnum.LOGIN_ERROR);

        Map<String, Object> params = new HashMap<>();
        params.put("sub",manager.getId());
        params.put("iat",new Date());
        params.put("ip",getClientIp(request));
        String token = TokenUtil.createToken(params,signature);
        redisTemplate.opsForValue().set(token,"",30, TimeUnit.MINUTES);
        return R.ok(new LoginResult(token,manager.getUserName()));
    }

    private String getClientIp(HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if(ip != null && ip.contains(",")){
            ip = ip.split(",")[0];
        }
        return ip;
    }
}
